package com.key.w8.common;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;

/**
 * @Author: k8
 * @CreateTime: 2025-02-19
 * @Version: 1.0
 *
 */
/**
 * 每当有写操作发生，则通过回调writeListener更新时间
 */

public class ReadOrWriteTimeHolder  extends ChannelDuplexHandler {
    /**
     * 事件idle
     * */
    protected volatile long lastReadOrWriteTime = System.currentTimeMillis();
    private final long connectionTimeout;
    protected final ChannelFutureListener writeListener = future -> {
        if (future.isSuccess()) {
            this.lastReadOrWriteTime = System.currentTimeMillis();
        }
    };

    public ReadOrWriteTimeHolder(long connectionTimeout) {
        this.connectionTimeout = connectionTimeout;
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        ctx.write(msg, promise.unvoid()).addListener(writeListener);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        this.lastReadOrWriteTime = System.currentTimeMillis();
        ctx.fireChannelReadComplete();
    }

    /**
     * is current connection timeout
     * @return {@code true} if timeout, {@code false} if not
     */
    public boolean isTimeout() {
        return System.currentTimeMillis() - lastReadOrWriteTime > connectionTimeout;
    }

    public long getLastReadOrWriteTime() {
        return lastReadOrWriteTime;
    }



}
